<?php namespace App\Http\Controllers\Admin;

use App\Configs;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;

class SysController extends Controller
{
    public function getWelcome()
    {
        return view('admin.sys.welcome');
    }

    public function getRepass()
    {
        return view('admin.sys.repass');
    }

    public function postRepass(Request $request)
    {
//        $validator = $this->validate($request, [
//            //'opwd' => 'required',
//            'password' => 'required|confirmed',
//        ]);

        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];

        $validator = \Validator::make($request->all(), [
            'opwd' => 'required',
            'password' => 'required|confirmed|min:6|max:20',
        ], [], [
            'opwd' => '原密码',
            'password' => '新密码',
        ]);

        if ($validator->fails()) {
            $message = $validator->messages();
            if ($message->has('opwd')) {
                $ret['message'] = $message->first('opwd');
            } else {
                $ret['message'] = $message->first('password');
            }
        } else {
            if (\Auth::validate(['name' => \Auth::user()->name, 'password' => $request->input('opwd')])) {
                $user = \Auth::user();
                $user->password = bcrypt($request->input('password'));
                $user->save();
                $ret['state'] = 'success';
                $ret['message'] = '密码修改成功，下次登录请使用新密码';
            } else {
                $ret['message'] = '原密码错误';
            }
        }

        return \Response::json($ret);
    }

    public function getSetting()
    {
        $model = Config::get('site');
        return view('admin.sys.setting', [
            'model' => $model
        ]);
    }

    public function postSetting(Request $request)
    {
        abort(404);
        $data = $request->all();
        Config::set('site.title', $data['title']);
        return \Response::json(['state' => 'success', 'message' => '操作成功']);
    }

    public function getBase(){
        $pics = json_decode(Configs::findOrNew(1)['val']);
        $vedio = Configs::findOrNew(2);
        return view('admin.sys.config',[
            'pics'  => $pics,
            'vedio'  => $vedio
        ]);
    }

    public function postBase(Request $request){
        $pic = json_encode($request->get('pic'));
        $vedio = $request->get('content');
        $model = Configs::findOrNew(1);
        $model -> fill(['val'=>$pic]);
        $model -> save();
        $models = Configs::findOrNew(2);
        $models -> fill(['val'=>$vedio]);
        $models -> save();
        return \Response::json(['state' => 'success', 'message' => '操作成功']);
    }

    public function getChche(){
        Cache::flush();
        return redirect()->guest('/admin');
    }
}
